import axios from 'axios';
import router from '@/router';
import { AxiosCancel } from './cancel';
const axiosCancel = new AxiosCancel();
import { useMessage } from 'naive-ui'
const message = useMessage()

/**
 * 创建实例与后端服务通信
 */
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 10 * 1000, // 请求超时时间
  headers: { 'Content-Type': 'application/json;charset=UTF-8', 'x-platform': 'PC' },
  withCredentials: false,
});

/**
 * 请求拦截器
 * 功能：配置请求头
 */
service.interceptors.request.use((config) => {
  if (config.requestOptions) {
    for (const [key, value] of Object.entries(config.requestOptions)) {
      config.headers[key] = value;
    }
  }
  // 获取ticket
  const ticket = localStorage.getItem('ticket');
  if (ticket && config.ticket) {
    config.headers['ticket'] = ticket;
  }
  const token = localStorage.getItem('token');
  if (token) {
    config.headers['Authorization'] = token;
  }
  config.headers['uniPlatform'] = 'PC';
  return config;
}, error => {
  // 对请求错误做些什么
  return Promise.reject(error)
});

/**
 * 响应拦截器
 * 功能：处理异常
 */
service.interceptors.response.use(
  (response) => {
    const data = response.data;
    if (data.code === 2000 || data.code === 200) {
      return data.data;
    } else if (data.code === 6000) {
      // router.push('/login')
      message.error('抱歉，您的账号已被冻结，请联系管理员', { max: 1 })
    } else if (data.code === 5000) {
      if(router.currentRoute.value.fullPath == '/') {
        // router.push('/login')
      }else {
        if(router.currentRoute.value.fullPath.includes('redirec')) return false
        //跳转到login路由，并把目标路由的url路径保存在login的query中
        // router.replace({
        //   name: "login",
        //   query: {
        //     redirect: router.currentRoute.value.fullPath
        //   }
        // }).then(r => {})
      }
    } else {
      return data;
    }
  },
  (err) => {
    if (err.code === 'ERR_CANCELED') return;
    // 处理被取消的请求
    if (axios.isCancel(err)) return console.error('请求的重复请求：' + err.message);
    const messages = axiosCancel.httpErrorStatusHandle(err); // 处理错误状态码
    if (messages) {
      // message.error(messages);
      console.log(messages)
    }
    return Promise.reject(err.response);
  },
);

const request = {
  get({ url, params, ticket, message, config }) {
    return request.request('GET', url, { params }, ticket, message, config);
  },
  post({ url, data, ticket, message, config }) {
    return request.request('POST', url, { data }, ticket, message, config);
  },
  put({ url, data, ticket, message, config }) {
    return request.request('PUT', url, { data }, ticket, message, config);
  },
  delete({ url, data, ticket, message, config }) {
    return request.request('DELETE', url, { data }, ticket, message, config);
  },
  request(method = 'GET', url, data, ticket, message, config = {}) {
    return new Promise((resolve, reject) => {
      service({ method, url, ...data })
        .then((res) => {
          resolve(res);
        })
        .catch((e) => {
          reject(e);
        })
        .finally(() => {
        });
    });
  },
};

export default request;
